
/**
 * 报销页面前台逻辑实现 
 */

window.isNewCjkDialog = false; //是否是新打开的冲借款页面
window.isChangeFromFin = false;//是否是来自财务页签的出发事件，默认是

function getDjlx(){  
	return "bx";
}
function getHeadDs(){
	return getDataset("bx_bxzb");
}
function getSubDs(){
	return getDataset("bx_jkbxitems");
}

/**
 * 打开冲借款前校验    
 * @param ds
 * @return
 */
function $beforeOpenCjkCheck(ds){
	var ds = getDataset('bx_bxzb');
	var jkbxr = ds.getSelectedRow().getCellValue(ds.nameToIndex('jkbxr'));
	var isHK = getParameter('type');
	if(jkbxr == null || jkbxr == ''){
		showMessageDialog("${ml:trans('yer_bxmanage001')}");
		return false;
	}  
	if(isHK == null){
		var total = ds.getSelectedRow().getCellValue(ds.nameToIndex('total'));
		if(total == null || parseFloat(total) <= 0){ 
			showMessageDialog("${ml:trans('yer_bxmanage002')}");//请录入报销金额,再进行冲借款操作!
			return false;
		}
	}
	return true;
} 
/**
 * 页面参数
 * @return 
 */
function setPageParamMap(key,value){
	if(window.PageParamMap == null)
		window.PageParamMap = new HashMap();
	window.PageParamMap.put(key,value);
}
/**
 * 获取冲借款查询参数Map
 * @return map
 */
function $getParamMap(){
	var ds = getDataset('bx_bxzb');
	var jkbxr = ds.getSelectedRow().getCellValue(ds.nameToIndex('jkbxr'));
	var pk_jkbx = ds.getSelectedRow().getCellValue(ds.nameToIndex('pk_jkbx'));
	var ybje = ds.getSelectedRow().getCellValue(ds.nameToIndex('ybje'));
	var ischeck = ds.getSelectedRow().getCellValue(ds.nameToIndex('ischeck'));
	var bzbm = ds.getSelectedRow().getCellValue(ds.nameToIndex('bzbm'));
	var receiver = ds.getSelectedRow().getCellValue(ds.nameToIndex('receiver'));
	if(ischeck == 'true' || ischeck == 'Y'){
		ischeck = true;
	}else if(ischeck == 'false'|| ischeck == 'N'){
		ischeck = false;
	}
	var obj = "{javaClass:'java.util.HashMap',map:{jkbxr:'" + jkbxr
			+ "',ybje:'" + ybje;
		if(pk_jkbx == null)
			obj += "',pk_jkbx:null";
		else
			obj += "',pk_jkbx:'" + pk_jkbx + "'";
		if(receiver == null)
			obj += ",receiver:null";
		else
			obj += ",receiver:'" + receiver + "'";
		obj += ",ischeck:" + ischeck +",bzbm:'" + bzbm + "'}}";
	return obj;
}
/**
 * 打开冲借款 
 */
function $openCjk(type){
	var ds = getDataset('bx_bxzb');
	if(!$beforeOpenCjkCheck())
		return;
	ds.reqParameterMap.clear();
	ds.addReqParameter("CJK_TYPE",type);
	/*载入数据在include.js中*/ 
	var bzbm = ds.getSelectedRow().getCellValue(ds.nameToIndex('bzbm'));
	var url = getCorePath() + "/cjk/listui.jsp?pageId=f_cjk&ctrl=nc.lfw.finance.ctrl.BXContrastManageController&bzbm="+bzbm;
	var id = 'contrast_dialogs';
	if(window.isNewCjkDialog){//首次加载冲借款框
		showDialog(url,"${ml:trans('yer_bxmanage003')}",'700','500',id,true);
		window.isNewCjkDialog = false;
	}else{
		var dialog = getCurrentDialog1();
		dialog.setSize('700', '500');
		dialog.setTitle("${ml:trans('yer_bxmanage003')}");//'冲借款信息'
		var cjkFrame = window["$modalDialogFrame" + id];
		dialog.getContentPane().appendChild(cjkFrame);
		dialog.show();
		showDialog.dialogCount ++;
		// iframe显示之前调用此方法(父调用子)
		if(cjkFrame.contentWindow.onBeforeActive != null)
	  		cjkFrame.contentWindow.onBeforeActive();
	}
}

function getCurrentDialog1(isOpen) {
	var dialogName = null;
	if(isOpen == null || isOpen == false)
		dialogName = "$modalDialog" + (showDialog.dialogCount);
	else
		dialogName = "$modalDialog" + (showDialog.dialogCount - 1);
	return window[dialogName];
}

/**
 * 初始化
 */
function initJkBx() {
	billUI.eventHandler.noCjk = true;
	var headDs = getDataset('bx_bxzb');
	//行选中状态变换，undo情况下，都需要更新按钮状态
    if(headDs != null){
		headDs.onAfterRowUnSelect = function(event){
			var indices = this.getSelectedIndices();
			if(indices.length == 1){
	   			var row = this.getSelectedRow();
	   			this.setRowSelectedByRowId(row.rowId)	
			}
		}
		
    }
    //摘要的參照框不需要派發事件
    var zyEle = getComponent('headTab_bxzb_form').getElement('zy_mc'); 
    	if(zyEle != null){
    		zyEle.innerProcessEnter = function(){
    		var zy_mc = getComponent('headTab_bxzb_form').getElement('zy_mc').getValue();
    		headDs.setValueAt(headDs.getSelectedIndex(),headDs.nameToIndex('zy'),zy_mc);
    	}
    }
	
	//如果选中的tab页发生变换，需要更新按钮状态
	getComponent("bodyTab").afterActivedTabItemChange = function(currItem) {
		ButtonManager.getInstance().updateButtons();
		//将表头精度设入财务
		if(currItem.name == 'er_finitem'){
				if(window.PageParamMap != null){
					var currPre = window.PageParamMap.get('precision');
					if(currPre == null) return;
					var finGrid = getComponent('bodyTab_er_finitem_grid');
					var ele = finGrid.getHeader('cjkybje');
					if(	ele.precision != currPre){
						$$resetFinPrecision(currPre);//先
						$resetFinItemBb(getDataset('bx_fin'));//后
					}
				}
		}
	};
	
/*******************************主表字段变化 START******************************************************/

	//主表数据发生变化，需要处理的逻辑定义
	headDs.onAfterDataChange = function(event){
		var ybArr = ['ybje','ybye','hkybje','zfybje','cjkybje'];
		var bbArr = ['bbje','bbye','hkbbje','zfbbje','cjkbbje'];
		
		var arrhead = getSessionAttribute("head_reim_field");
		if(arrhead != null){
			var arrheadsplipt = arrhead.split(",");
			for(var j = 0; j < arrheadsplipt.length; j++) {
				headindex = headDs.nameToIndex(arrheadsplipt[j]);
				if(event.cellColIndex == headindex) {
					doHeadDataChange();
				}
			}
		}
		
		/*【币种】变化，则汇率变化,主表的精度、本币金额变化、汇率可写；原币可写*/
		if(event.cellColIndex == this.nameToIndex("bzbm")){
			if(event.currentValue == event.oldValue)
				return; 
			window.isNewCjkDialog = true;//收款人字段变化，则重新加载冲借款
			reset4Bzbm(this, event.currentValue, "bx");
			//如果是还款单，币种改变，则清空表体、表头金额，重新选择
			var type = getParameter('type');
			if(type != null && type == 'hk'){
				window.isNewCjkDialog = true;
				var cDs = getDataset("bx_contrast");
				cDs.deleteRows(-1);
				var arr = ['ybye','hkybje','zfybje','cjkybje'];
				for(var ii=0; ii<arr.length; ii++)
					this.setValueAt(0,this.nameToIndex(arr[ii]),0);
			}
			
			cleanFinJe();
		}
		/*汇率*/
		if(event.cellColIndex == this.nameToIndex("bbhl")){
			resetJEforHl('bx');
		}
		/*原币、本币*/
		for(var k=0,len = ybArr.length; k<len; k++){
			if(event.cellColIndex == this.nameToIndex(ybArr[k])){
 				var bbIndex = this.nameToIndex(bbArr[k]);
 				var bbhl = event.currentRow.getCellValue(headDs.nameToIndex('bbhl'));
				headDs.setValueAt(event.cellRowIndex, bbIndex, parseFloat(event.currentValue)*parseFloat(bbhl));
				if(ybArr[k] == 'ybje'){
					if(!window.isChangeFromFin){//是否是来自财务页签触发
						
						isAction = true;//如果是原币金额改变，则不需要再出发busItemTabRowChange1方法
						bxzbDataChange("ybje");
						isAction = false;
					}else{
						window.isChangeFromFin = false;
					}
				}
			}
		} 
		
		/*合计金额*/
		if(event.cellColIndex == this.nameToIndex('total')){
			if(isRefresh || isCopy){//如果是刷新操作后，则return 
				return; 
			}
			if(event.currentValue == null || event.currentValue == '')
				return;
			if(event.currentValue != 0){
				this.setValueAt(event.cellRowIndex, this.nameToIndex('ybje'),$f(event.currentValue));
			}
		}
		/*收支项目变化，则表体对应收支 改！！！*/
		if(event.cellColIndex == this.nameToIndex('szxmid')){
			var busDs = getDataset('bx_jkbxitems');
			if(busDs == null) 
				return;
			
			if(isSave){//保存操作后表头不影响表体收支项目
				isSave = false;
				return;
			}
			
			var count = busDs.getRowCount();
			for(var i=0; i < count; i++){
				var index = busDs.nameToIndex('szxmid');
				busDs.setValueAt(i,index,event.currentValue,true);
			}
			if(event.currentValue != null && event.currentValue != event.oldValue)
				bxzbDataChange("szxmid");
		}
		/*预算变，则将财务页签中全变*/
		if(event.cellColIndex == this.nameToIndex('jobid')){
			var finDs = getDataset('bx_fin');
			if(finDs != null){
				var jobIdIndex = finDs.nameToIndex('jobid');
				var jobMcIndex = finDs.nameToIndex('jobid');
				if(colIndex != -1){
					var jobmc = event.currentRow.getCellValue(this.nameToIndex('jobid_mc'));
					for(var i=0,len=finDs.getRowCount();i<len;i++){
						finDs.setValueAt(i,jobIdIndex,event.currentValue,false);
						finDs.setValueAt(i,jobMcIndex,jobmc,false);
					}
				}
			}
		}
		/*收款人*/
		if(event.cellColIndex == this.nameToIndex('receiver')){
			window.isNewCjkDialog = true;//收款人字段变化，则重新加载冲借款
		}
		/*报销人*/
		if(event.cellColIndex == this.nameToIndex('jkbxr')){
			if(isAdd)
				return;
			//重新获取个人银行账号
			window.isNewCjkDialog = true;//收款人字段变化，则重新加载冲借款
			//重新获取个人银行账号
			var strs = getService("webbx_common_service").getFromJkbxrChange(event.currentValue);
			if(strs == null){
				this.setValueAt(this.getSelectedIndex(),this.nameToIndex('skyhzh'),null,false);
				this.setValueAt(this.getSelectedIndex(),this.nameToIndex('skyhzh_mc'),null,false);
			}else{
				var arr = eval(strs);
				var row = this.getSelectedRow();
				this.setValueAt(event.cellRowIndex,this.nameToIndex('skyhzh'),arr[1],false);
				this.setValueAt(event.cellRowIndex,this.nameToIndex('skyhzh_mc'),arr[2],false);
				
				/*
				报销部门和费用承担部门都应该随之变成报销人所在部门。
				注意如果费用承担公司与报销公司不一致，费用承担部门不要变。
				*/
				this.setValueAt(event.cellRowIndex,this.nameToIndex('deptid'),arr[0],true);
		
				var dwbm = event.currentRow.getCellValue(this.nameToIndex("dwbm"));
				var fydwbm = event.currentRow.getCellValue(this.nameToIndex("fydwbm"));
				if(dwbm != null && fydwbm != null && dwbm == fydwbm){
					this.setValueAt(event.cellRowIndex,this.nameToIndex('fydeptid'),arr[0],true);
				}
			}
			
			
			//重置财务的报销人
			var finDs = getDataset('bx_fin');
			if(finDs != null){
				var colIndex = finDs.nameToIndex('jkbxr');
				for(var i=0,count=finDs.getRowCount();i<count; i++)
					finDs.setValueAt(i,colIndex,event.currentValue,true);
			}
			dealRuleAction();
		}
		//TODO ? 表头项目变化，则重置财务页签所有行的 项目
		//TODO ? 表头资金计划项目变化，则重置财务页签所有行的 项目
	}
/**********************************主表变化 END***************************************************/

	/*冲销明细*/
	var cDs = getDataset("bx_contrast");
	cDs.onAfterDataChange = function(event){
		var ybArr = ['ybje','fyybje','cjkybje'];
		var bbArr = ['bbje','fybbje','cjkbbje'];
		for(var i=0,len = ybArr.length; i<len; i++){
			if(event.cellColIndex == this.nameToIndex(ybArr[i])){
				if(headDs.getSelectedRow() != null){
					var bbhlIndex = headDs.nameToIndex('bbhl');
					var bbhlValue = headDs.getSelectedRow().getCellValue(bbhlIndex);
					
					var bbIndex = this.nameToIndex(bbArr[i]);
					var ybIndex = this.nameToIndex(ybArr[i]);
					var ybValue = this.getRow(event.cellRowIndex).getCellValue(ybIndex);
					this.setValueAt(event.cellRowIndex, bbIndex, parseFloat(ybValue)*parseFloat(bbhlValue));
					
				}
			}
		}
	}
	/*单据执行“增加”动作后执行*/
	billUI.eventHandler.onAfterBoAdd = function(newRow)
	{ 
		$resetPageStatus();
		//进行常用单据设置
		var cydjArrStr = getSessionAttribute("cydj");
		if(cydjArrStr == null)
			return;
		//isCydj = true;
		var cydjArr = eval(cydjArrStr);
		var bxitemDs = getDataset("bx_jkbxitems");
		if(bxitemDs == null)
			return;
		for(var i = 0,len = cydjArr.length; i < len; i ++){
			var row = bxitemDs.getEmptyRow();
			row.cydj = true;
			for(var j = 0,mlen = bxitemDs.metadata.length; j < mlen; j ++){
				var value = cydjArr[i][bxitemDs.metadata[j].key];
				if(value != null)
					row.setCellValue(j, value);
			}
			bxitemDs.addRow(row, false);
			
		}
		 dealRuleAction();
	};
	
	/*单据执行“编辑”动作后执行*/
	billUI.eventHandler.onAfterBoEdit = function(newRow)
	{
		$resetPageStatus();
		//修改外币单据，本币汇率可编辑
		var jtbwb = getSessionAttribute("jtbwb");
		var bbhlEle = getComponent("headTab_bxzb_form").getElement("bbhl");
		var bzbm = headDs.getSelectedRow().getCellValue(headDs.nameToIndex('bzbm'));
		if(jtbwb != bzbm){
			if(bbhlEle != null) 
				bbhlEle.setActive(true);
		}
		
		dealRuleAction();
	};
	
	//billUI.eventHandler.onBeforeBoLineIns = billUI.eventHandler.onBeforeBoLineAdd;
	
	var bxitemsDs = getDataset("bx_jkbxitems");
	if(bxitemsDs != null)
		$initBusItems(bxitemsDs,headDs);
	
	var finDs = getDataset("bx_fin");
	if(finDs != null)
		$initFinDs(finDs,headDs);
}

/**
 *初始化表体业务页签
 */
function $initBusItems(bxitemsDs,headDs){
	
	bxitemsDs.onAfterRowDelete = function(event){
		if(this.getRowCount() >= 0)
			busItemTabRowChange();
	}
	bxitemsDs.onBeforeRowInsert = function(rowIndex, rows){
		jkbxBeforeBoLineAdd(rows[0], this);
	}
	bxitemsDs.onAfterRowInsert = function(event){
		doBodyDataChange();
		busItemTabRowChange();
	}
	bxitemsDs.onAfterDataChange = function(event){
		var amountIndex = this.nameToIndex("amount");// 报销金额
		var s1SzxmIndex = this.nameToIndex("szxmid");// 收支项目
		var headDs = getDataset('bx_bxzb');
		var bxitemsDs = getDataset("bx_jkbxitems");
		if(bxitemsDs == null)
			return;
		//对表体有影响的字段
		var arrbody = getSessionAttribute("body_reim_field");
		if(arrbody != null){
			var arrsplit = arrbody.split(",");
			for(var i = 0; i < arrsplit.length; i++) {
				index = bxitemsDs.nameToIndex(arrsplit[i]);
				if(event.cellColIndex == index) {
		   			doBodyDataChange();
		   		}
			}
		}
		
		/*报销金额列改变*/
		if(event.cellColIndex == amountIndex ){
			var pre = null;
			if(window.bzbmmap != null){
				pre = window.bzbmmap.get(headDs.getSelectedRow().getCellValue(headDs.nameToIndex('bzbm')));
			}
			if(pre == null)
				pre = getSessionAttribute("precision");
			var newSum = this.totalSum(["amount"], null, null, pre);
			headDs.setValueAt(headDs.getSelectedIndex(), headDs.nameToIndex("total"), newSum[0]);//设置表头合计金额
			busItemTabRowChange();
		}
		/*收支项目列改变*/
		if(event.cellColIndex == s1SzxmIndex){
			var row = event.currentRow;
			if(row == null)
				return;
			busItemTabRowChange();
		}
	}
}

/**
 *初始化表体财务页签
 */
function $initFinDs(finDs,headDs){
	finDs.onAfterDataChange = function(event){
		/*财务页签的原币金额总计变化触发表头的相应原币变化;并且根据本币汇率设置本币金额 */
		if(this.headTrigger){
			this.headTrigger = false;
			return;
		}
		var ybArr = ['ybje','ybye','hkybje','zfybje','cjkybje'];
		var bbArr = ['bbje','bbye','hkbbje','zfbbje','cjkbbje'];
		for(var i=0,len = ybArr.length; i<len; i++){
			if(event.cellColIndex == this.nameToIndex(ybArr[i])){
				if(headDs.getSelectedRow() != null){
					var bbhlIndex = headDs.nameToIndex('bbhl');
					var bbhlValue = headDs.getSelectedRow().getCellValue(bbhlIndex);
					var pre = null;
					if(window.bzbmmap != null){
						pre = window.bzbmmap.get(headDs.getSelectedRow().getCellValue(headDs.nameToIndex('bzbm')));
					}
					if(pre == null)
						pre = getSessionAttribute("precision");
						
					var newSum = this.totalSum([ybArr[i]], null, null, pre);
					headDs.setValueAt(headDs.getSelectedIndex(), headDs.nameToIndex(ybArr[i]), newSum[0]);
					window.isChangeFromFin = true;
					setBbje(ybArr[i],bbArr[i],event.cellRowIndex,bbhlValue);				
				}
			}
		}
		/*财务页签 本币合计变化触发表头本币变化*/
		for(var k=0,len = bbArr.length; k<len; k++){
			if(event.cellColIndex == this.nameToIndex(bbArr[k])){
				var newSum = this.totalSum([bbArr[k]], null, null, getSessionAttribute("precision"));
				headDs.setValueAt(headDs.getSelectedIndex(), headDs.nameToIndex(bbArr[k]), newSum[0]);
			}
		}
	}
}

/**
 * 根据本币汇率来设置财务页签Fin的本币 【本币金额、本币余额、还款本币金额、支付本币金额、冲借款本币金额】
 */
function setBbje(yb,bb,rowIndex,newHl){
	var finDs = getDataset('bx_fin');
	var bbIndex = finDs.nameToIndex(bb);
	var ybIndex = finDs.nameToIndex(yb);
	var ybValue = finDs.getRow(rowIndex).getCellValue(ybIndex);
	finDs.setValueAt(rowIndex, bbIndex, parseFloat(ybValue)*parseFloat(newHl));
};


function yesTodo(){
	$openCjk("unusual");
};
function notTodo(){
	billUI.eventHandler.noCjk = false;
	billUI.eventHandler.onBoSave();
	cleanParam();
};

function adjustSpliterSelf(billUI) {
	try{
		var bodyHeight = document.body.offsetHeight;
		var bodyTab = getComponent("bodyTab");
		if(billUI.currentPanel == ManageUI.LISTPANEL){
			var headGrid = getComponent("headTab_bxzb_grid");
			var goldHeight = (bodyHeight - 50) * 0.42;
			$('toptr').style.height = goldHeight;
			//bodyTab.getItemByName("er_bxcontrast").hide();
			//bodyTab.hideItem("er_bxcontrast");
			// 如果隐藏的是当前的激活控件,则激活第一个非隐藏页签
			if(bodyTab.activedItem == bodyTab.getItemByName("er_bxcontrast"))
				bodyTab.activeTab(bodyTab.getFirstVisibleItemIndex());
		}
		else{
			var headTab = getComponent("headTabCard");
			var height = 12;
			if(headTab != null && headTab.tabItems.length > 1){
				height += 14;
			}
			var itemName = headTab.tabItems[0].name;
			var headForms = getComponents(AutoFormComp);
			//以第一个选中项的所有表单和为准，多于一个的表单为fieldset组织，额外加上20px；
			for(var i = 0; i < headForms.length; i ++){
				if(headForms[i].id.startWith("headTab_")){
					height += headForms[i].getHeight();
					if(i > 0)
						height += 20;
				}
			}
			//var headForm = getComponent("headTab_bxzb_form");
			//height += headForm.getHeight();
			var goldHeight = (bodyHeight - 50) * 0.42;
			if(height > goldHeight){
				$('toptr').style.height = goldHeight;
			}
			else
				$('toptr').style.height = height;
			//bodyTab.getItemByName("er_bxcontrast").show();
			//bodyTab.showItem("er_bxcontrast");
			
			var tailForm = getComponent("tailTab_tail_form");
			if(tailForm != null){
				$('tailtr').style.height = tailForm.getHeight();
			}
		}
	}
	catch(error){
		log("Error occurred while adjusting spliter!");
	}
};


//因为焦点触发问题而注释掉，不然在增行后直接保存，未触发事件
function busItemTabRowChange() {
	if(window.$fin_rt != null){
		clearTimeout(window.$fin_rt);
	}
	window.$fin_rt = setTimeout("busItemTabRowChange1()", 50);
}


/**
 * 业务信息页签的行数据变化对财务页签触发
 */
function busItemTabRowChange1() {

	if((ButtonManager.getInstance().operStatus != IBillOperate.OP_ADD )
		&& (ButtonManager.getInstance().operStatus !=  IBillOperate.OP_EDIT ))
		return;
	if(isCopy || isAction){
		return;
	}
	var headDs = getDataset('bx_bxzb');
	if(headDs == null || headDs.getSelectedRow() == null)
		return;
	var cjk_sum = headDs.getSelectedRow().getCellValue(headDs.nameToIndex('cjkybje'));
	var ybje = headDs.getSelectedRow().getCellValue(headDs.nameToIndex('ybje'));
	var finDs = getDataset('bx_fin');
	var ybjeIndex = finDs.nameToIndex("ybje");
	var szxmIndex = finDs.nameToIndex("szxmid");
	var bxBusiDs = getDataset('bx_jkbxitems');
	var busiRows = bxBusiDs.getRows();
	var map = new Object;
	//先按照收支项目进行分类
	if (busiRows != null) {
		var busiSzxmIndex = bxBusiDs.nameToIndex("szxmid");
		var amountIndex = bxBusiDs.nameToIndex("amount");
		for ( var i = 0,len = busiRows.length; i < len; i++) {
			var busiRow = busiRows[i];
			var valueArr = map[busiRow.getCellValue(busiSzxmIndex)];
			if (valueArr == null) {
				valueArr = new Array;
				map[busiRow.getCellValue(busiSzxmIndex)] = valueArr;
			}
			var value = busiRow.getCellValue(amountIndex);
			if (value != null && value != "")
				valueArr.push(value);
		}
	}
	var finRows = finDs.getRows();
	if (finRows != null) {
		for ( var i = finRows.length - 1; i >= 0; i--) {
			var szxmId = finRows[i].getCellValue(szxmIndex);
			var valueArr = map[szxmId];
			map[szxmId] = null;
			if (valueArr == null)
				finDs.deleteRow(i);
			else {
				var total = 0;
				for ( var j = 0,vlen = valueArr.length; j < vlen; j++) {
					total += parseFloat(valueArr[j]);
				}
				//finDs.setValueAt(i, ybjeIndex, total);
				finRows[i].setCellValue(ybjeIndex, total);
				$setDefaultBodyData(i);
			}
		}
		if(finDs.getRowCount() > 0) {
			finDs.setValueAt(0, ybjeIndex, finDs.getValueAt(0, ybjeIndex));
		}
	}
	for (var i in map) {
		if (map[i] != null) {
			var valueArr = map[i];
			var total = 0;
			for ( var j = 0; j < valueArr.length; j++) {
				total += parseFloat(valueArr[j]);
			}
			var newRow = finDs.getEmptyRow();
			newRow.setCellValue(ybjeIndex, total); 
			if(i == 'null' || i == '' || i == null)
				newRow.setCellValue(szxmIndex, null);
			else
				newRow.setCellValue(szxmIndex, i);

			var newnewRow = $initDefaultBodyData(newRow);
			finDs.addRow(newnewRow);
		}
	}
	//当子表删除完了后，因为不会触发bx_fin，所以需要显式的将headds中的金额归零（除过cjkybje）
	if(finDs.getRowCount() == 0){
		var index = headDs.getSelectedIndex();
		var ybArr = ['ybje','ybye','hkybje','zfybje'];
		for(var t=0;t<ybArr.length;t++)
			headDs.setValueAt(index,headDs.nameToIndex(ybArr[t]),0);
	}
	//重新将财务页签中的 值设置
	
	//if($f(cjk_sum) > 0){
		setFinCjk(cjk_sum,$f(ybje));
	//}
};

function $setDefaultBodyData(rowIndex){
	var finDs = getDataset('bx_fin');
	var headDs = getDataset('bx_bxzb');
	//资金计划项目
	var cashprojIndex = headDs.nameToIndex('cashproj');
	if(cashprojIndex != -1){
		var cashproj = headDs.getSelectedRow().getCellValue(cashprojIndex);
		var cashproj_mc = headDs.getSelectedRow().getCellValue(headDs.nameToIndex('cashproj_mc'));
		finDs.setValueAt(rowIndex, finDs.nameToIndex('cashproj'), cashproj,false);
		finDs.setValueAt(rowIndex, finDs.nameToIndex('cashproj_mc'), cashproj_mc,false);
	}
	//项目
	var jobIndex = headDs.nameToIndex('jobid');
	if(jobIndex != -1){
		var job = headDs.getSelectedRow().getCellValue(jobIndex);
		var job_mc = headDs.getSelectedRow().getCellValue(headDs.nameToIndex('jobid_mc'));
		finDs.setValueAt(rowIndex, finDs.nameToIndex('jobid'), job, false);
		finDs.setValueAt(rowIndex, finDs.nameToIndex('jobid_mc'), job_mc, false);
	}
	//报销人
	var jkbxr = headDs.getSelectedRow().getCellValue(headDs.nameToIndex('jkbxr'));
	var jkbxr_mc = headDs.getSelectedRow().getCellValue(headDs.nameToIndex('jkbxr_mc'));
	finDs.setValueAt(rowIndex,finDs.nameToIndex('jkbxr'), jkbxr, false);
	finDs.setValueAt(rowIndex,finDs.nameToIndex('jkbxr_mc'), jkbxr_mc, false);
}

function $initDefaultBodyData(newRow){
	var headDs = getDataset('bx_bxzb');
	var finDs = getDataset('bx_fin');
	//资金计划项目
	var cashprojIndex = headDs.nameToIndex('cashproj');
	if(cashprojIndex != -1){
		var cashproj = headDs.getSelectedRow().getCellValue(cashprojIndex);
		var cashproj_mc = headDs.getSelectedRow().getCellValue(headDs.nameToIndex('cashproj_mc'));
		newRow.setCellValue(finDs.nameToIndex('cashproj'), cashproj);
		newRow.setCellValue(finDs.nameToIndex('cashproj_mc'), cashproj_mc);
	}
	//项目
	var jobIndex = headDs.nameToIndex('jobid');
	if(jobIndex != -1){
		var job = headDs.getSelectedRow().getCellValue(jobIndex);
		var job_mc = headDs.getSelectedRow().getCellValue(headDs.nameToIndex('jobid_mc')); 
		newRow.setCellValue(finDs.nameToIndex('jobid'), job);
		newRow.setCellValue(finDs.nameToIndex('jobid_mc'), job_mc);
	}
	//报销人
	var jkbxr = headDs.getSelectedRow().getCellValue(headDs.nameToIndex('jkbxr'));
	var jkbxr_mc = headDs.getSelectedRow().getCellValue(headDs.nameToIndex('jkbxr_mc'));
	newRow.setCellValue(finDs.nameToIndex('jkbxr'), jkbxr);
	newRow.setCellValue(finDs.nameToIndex('jkbxr_mc'), jkbxr_mc);
	return newRow;
}

/*复制新增后，处理*/
BillEventHandler.prototype.onAfterBoCopyAdd = function(row)
{
	window.isNewCjkDialog = true;//初始化冲借款框
	billUI.eventHandler.noCjk = true;
	dealRuleAction();
}

function setParam(obj){
	window.objs = obj;
}
function cleanParam(){
	window.objs = null;
}

/*********************************************/
//暂存时清空冲借款信息
function clernCjk(){
	//如果是还款单据，设置主表的页签值
	var headDs = getDataset('bx_bxzb');
	var type = getParameter('type'); 
	if(type != null && type == 'hk'){
		headDs.setValueAt(headDs.getSelectedIndex(),headDs.nameToIndex('cjkybje'),0,true);
		headDs.setValueAt(headDs.getSelectedIndex(),headDs.nameToIndex('hkybje'),0,true);
	}else{
		//设置财务页签金额
		setFinCjk(0, 0);
	}
	//清空冲销页签
	var cDs = getDataset('bx_contrast');
	cDs.deleteRows(-1);
	return true;
}


/*
 * 1、冲借款时调用，设置财务中的各个金额字段[还调自己的]
 * 2、业务页签的amount、收支项目 变化 后如果之前已冲借款、则调用重新设置一遍
 * jkye_sum 冲借款
 * 
 */
function setFinCjk(jkye_sum,ybje){
	var finDs = getDataset("bx_fin");
	if(finDs == null)
		return;
	var finRowCount = finDs.getRowCount();
	var ybjeIndex = finDs.nameToIndex('ybje');
	//设置 cjkybje、 hkybje、 zfybje 的值
	for(var i = 0; i < finRowCount; i++){
		var finYbje = parseFloat(finDs.getRow(i).getCellValue(ybjeIndex));//财务每一行的ybje
		//如果剩余的冲借款金额不大于原币金额，则该项的冲借款金额值设为剩余的冲借款金额
		if(jkye_sum > finYbje){
			finDs.setValueAt(i,finDs.nameToIndex('cjkybje'),finYbje);
			finDs.setValueAt(i,finDs.nameToIndex('zfybje'),0);
			finDs.setValueAt(i,finDs.nameToIndex('hkybje'), 0); 
			jkye_sum -= finYbje;
		}
		else{
			finDs.setValueAt(i,finDs.nameToIndex('cjkybje'),jkye_sum);
			finDs.setValueAt(i,finDs.nameToIndex('zfybje'),finYbje - jkye_sum);
			finDs.setValueAt(i,finDs.nameToIndex('hkybje'),0); 
			jkye_sum = 0;
		}
	}
	if(jkye_sum > 0) { 
		var oldCjkybje = finDs.getValueAt(finRowCount - 1, finDs.nameToIndex('cjkybje'));
		var oldHkybje = finDs.getValueAt(finRowCount - 1, finDs.nameToIndex('hkybje'));
		finDs.setValueAt(finRowCount - 1, finDs.nameToIndex('cjkybje'), $f(oldCjkybje) + $f(jkye_sum));
		finDs.setValueAt(finRowCount - 1, finDs.nameToIndex('hkybje'), $f(oldHkybje) + $f(jkye_sum));
	}
}

/************************************报销标准***************************************/
//设置表头数据
function setJkBxHeadDsValue(value){
	var ds = getDataset('bx_bxzb');
	ds.setValueAt(ds.getSelectedIndex(),ds.nameToIndex('reimrule'),value);
}

/************************************报销标准***************************************/
//设置表头数据
function setJkBxHeadDsValue(value){
	var ds = getDataset('bx_bxzb');
	ds.setValueAt(ds.getSelectedIndex(),ds.nameToIndex('reimrule'),value);
}

//设置表体数据
function setJkBxBodyDsValueAno(parm){
	var resultofbody = eval(parm);
	var ds = getDataset('bx_jkbxitems');
	var tableCodeIndex = ds.nameToIndex('tablecode');
	for(var j = 0,len = resultofbody.length; j < len; j++) {
			var rowresult = resultofbody[j];
			var rowsplitresult = rowresult.split(",");
			var tabcode = rowsplitresult[0];
			var rowindex = rowsplitresult[2];
			var grid = getComponent("bodyTab_"+tabcode+"_grid");
			var grow = grid.model.getRow(rowindex).rowData;
			var drowIndex = ds.getRowIndex(grow);
			var value = rowsplitresult[1];
			var itemkey = rowsplitresult[3];
			ds.setValueAt(drowIndex, ds.nameToIndex(itemkey) , value);
		}
}
	

/*子表tablecode，自定义编辑公式Map*/
function getBodyList(){
	var bodyTab = getComponent("bodyTab");
	var items = bodyTab.getTabItems();
	var ds = getDataset("bx_jkbxitems");
	if(ds.getRowCount() <= 0)
		return null;
	var outstr = "{javaClass:'java.util.HashMap',map:{";
	for(var i=0,len=items.length;i<len;i++){
		var tabcode = items[i].name;
		if(tabcode == 'er_finitem' || tabcode == 'er_bxcontrast')
			continue;
		outstr += tabcode + ":" + $getBodyMap(tabcode,ds);
		if(i != len-1)
			outstr += ",";
		
	}
	outstr += "}}";
	return outstr;
}
 
/*一个子表的table，自定义编辑公式Map*/
function $getBodyMap(tabcode,ds){
		var grid = getComponent("bodyTab_"+tabcode+"_grid");
		if(grid == null)
			return null;
		var headers = grid.basicHeaders;
		var str = "{javaClass:'java.util.HashMap',map:{";
			var strArr = new Array;
		for(var k=0,len=headers.length;k<len;k++){
			var field = ds.getField(headers[k].keyName);
			var defFor = field.defEditFormular;
			var flag = false;
			if(defFor != null && defFor != ''){
				strArr.push(field.key + ":'" + defFor +"'");
			}
		}
			str += strArr.join(",");
			str += "}}";
		return str;
}

/*子表ds list*/
function getBodyDsListMap(){
	var str = new StringBuffer("{javaClass:'java.util.ArrayList',list:[");
	var busDs = getDataset('bx_jkbxitems');
	if(busDs != null){
		if(busDs.getRowCount() == 0)
			return null;
		var tmp = $getDsMapString(busDs);
		if(tmp != '')
			str.append(tmp +"]}");
		else 
			str.append(null); 
	}
	return str.toString();
}

/*一个子表map*/
function $getDsMapString(ds){
	var str = new StringBuffer();
	for(k=0,len=ds.getRowCount();k<len;k++){
		str.append("{javaClass:'java.util.HashMap',map:{");
		var row = ds.getRow(k);
		for(var i = 0,count=ds.metadata.length; i < count; i ++){
			var md = ds.metadata[i];
			var value = row.getCellValue(i);
			var replaceField = md.field.replace(".", "_$_");
			if(value != null)
				str.append(replaceField + ":'" + value+"'");
			else
				str.append(replaceField + ":null");
			if( i != count-1)
				str.append(",");
		}
		if(k != len-1)
			str.append("}},");
		else 
			str.append("}}");
	}
	return str.toString();
}


/*子表数据类型list*/
function getBodyDsDataTypeList(){
	var str = "{javaClass:'java.util.ArrayList',list:["
	var busDs = getDataset('bx_jkbxitems');
	if(busDs != null){
		var tmp = getDsDataTypeMapString(busDs);
		if(tmp != '')
			str += tmp +"]}";
		else str = null; 
	}
	return str;
}


/*一个子表数据类型map*/
function getDsDataTypeMapString(ds){
	var str = new StringBuffer();
	for(k=0,len=ds.getRowCount();k<len;k++){
		str.append("{javaClass:'java.util.HashMap',map:{");
		var row = ds.getRow(k);
		for(var i = 0; i < ds.metadata.length; i ++){
			var md = ds.metadata[i];
			var replaceField = md.field.replace(".", "_$_");
			if(md.dataType != null)
				str.append(replaceField + ":'" + md.dataType+"'");
			else 
				str.append(replaceField + ":null");
			if(i != ds.metadata.length-1)
				str.append(",");
		}
		if(k != len-1)
			str.append("}},");
		else 
			str.append("}}");
	}
	return str.toString();
}


/*主表数据类型map*/
function getHeadDsDataTypeMap(){
	var ds = getDataset('bx_bxzb');
	var str = new StringBuffer("{javaClass:'java.util.HashMap',map:{");
	var strArray = new Array();
	for(var i = 0,len=ds.metadata.length; i < len; i ++){
		var md = ds.metadata[i];
		var replaceField = md.field.replace(".", "_$_");
		if(md.dataType != null)
			strArray.push(replaceField + ":'" + md.dataType+"'");
		else
			strArray.push(replaceField + ":" + null);
	}
	str.append(strArray.join(","));
	str.append("}}");
	return str.toString();
} 


/*主表dsmap*/
function getHeadDsMap(){
	var ds = getDataset('bx_bxzb');
	var row = ds.getSelectedRow();
	var str = "{javaClass:'java.util.HashMap',map:{";
	var strArray = new Array();
	for(var i = 0,len=ds.metadata.length; i < len; i ++){
		var md = ds.metadata[i];
		var value = row.getCellValue(i);
		
		//**************************************TODO
		if(md.field == 'reimrule' || md.field == 'zyx10')
			value = null;;
		var replaceField = md.field.replace(".", "_$_");
		
		if(value != null)
			strArray.push( replaceField + ":'" + value+"'");
		else
			strArray.push(replaceField + ":" + value);
	}
	str += strArray.join(",");
	str += "}}";
	return str;
}

/*字符串拼接*/
function StringBuffer(str){   
    this.data = new Array();
    this.data.push(str);
}   
StringBuffer.prototype.append = function(str){   
     this.data.push(str);   
     return this;
};   
StringBuffer.prototype.toString = function(){   
    var str = arguments.length == 0 ? '' : arguments[0];   
    return this.data.join(str);   
}; 

